import { Toast } from 'vant'
import { navigateTo } from "@/router/index";
// 防抖 
export function debounceFunc(fn, wait = 500) {
    var timer = null;
    return function () {
        var context = this
        var args = arguments
        if (timer) { //有事件 清空
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(function () {
            fn.apply(context, args)
        }, wait)
    }
}
// 节流 每几秒执行一次
export function throttleFunc(func, marginTime = 10) {
    let lastTime = null
    return function () {
        let currentTime = +new Date()
        if (currentTime - lastTime > marginTime || !lastTime) {
            func.apply(this, arguments)
            lastTime = currentTime
        }
    }
}

// 邮箱验证
export function validateEmail(email) {
    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// 移动端验证
export function isMobile() {
    const flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    return flag ? true : false;
}

// 自定义指令
export function directiveFun(app) {
    app.directive('focus', {
        mounted(el) {
            el.focus()
        },
    })
}

export function dispatchEventStroage() {
    const signSetItem = localStorage.setItem
    localStorage.setItem = function (key, val) {
        let setEvent = new Event('setItemEvent')
        setEvent.key = key
        setEvent.newValue = val
        window.dispatchEvent(setEvent)
        signSetItem.apply(this, arguments)
    }
}

export function isWeChatBrowser() {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true // 微信中打开
    } else {
        return false // 普通浏览器中打开
    }
}


export function formatDate(cellValue) {
    if (cellValue == null || cellValue == "") return "";
    var date = new Date(cellValue)
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    return year + '-' + month + '-' + day
}

export function formatDateTime(cellValue) {
    if (cellValue == null || cellValue == "") return "";
    var date = new Date(cellValue)
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

// 复制文本内容到剪切板
export function copyToClipboard(text, isShowSuccessMsg) {
    if (!text.trim()) {
        Toast.fail('文本不存在')
        return
    }
    // 兼容非安全域，非安全域下不可使用navigator.clipboard.writeText
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard
            .writeText(text)
            .then(() => {
                isShowSuccessMsg && Toast.success('复制成功')
            })
            .catch(() => {
                // console.error('复制失败：', error)
            })
    } else {
        const textarea = document.createElement('textarea')
        textarea.value = text
        document.body.appendChild(textarea)
        textarea.select()
        document.execCommand('copy')
        document.body.removeChild(textarea)
        isShowSuccessMsg && Toast.success('复制成功')
    }
}
export function setLocalStorage() {
    // duration默认为30天，即2592000000毫秒（30天 * 24小时 * 60分钟 * 60秒 * 1000毫秒）
    const expirationTime = Date.now() + 2592000000;
    localStorage.setItem('expireTime', expirationTime);
}
